<script lang="ts" setup>
  import { watch, ref } from 'vue';
  import { useRouter, RouterView } from 'vue-router';
  import {
    IconHome,
    IconBook,
    IconComputer,
    IconQuestionCircle,
    IconGift,
  } from '@arco-design/web-vue/es/icon';
  interface CreatorMenu {
    title: string;
    key?: string;
    icon?: any;
    children?: CreatorMenu[];
  }
  const menus: CreatorMenu[] = [
    { title: '个人资料', key: 'CREATOR_HOME', icon: IconHome },
    {
      title: '账号设置',
      icon: IconBook,
    },
    {
      title: '消息设置',
      icon: IconComputer,
    },
    {
      title: '简历设置',
      icon: IconGift,
    },
    {
      title: '标签设置',
      icon: IconQuestionCircle,
    },
  ];

  const menuMap = new Map();
  const router = useRouter();
  const selectedKeys = ref<string[]>([]);

  travelMenus(menus);

  watch(
    router.currentRoute,
    ({ matched }) => {
      const matchedMenu = findMatchedMenu(matched);
      if (matchedMenu) {
        selectedKeys.value = [matchedMenu.key];
      }
    },
    { immediate: true },
  );
  watch(
    () => selectedKeys.value[0],
    (name) => {
      if (name !== router.currentRoute.value.name) {
        router.push({ name });
      }
    },
  );

  function travelMenus(menus) {
    menus.forEach((item) => {
      if (!item.children) {
        menuMap.set(item.key, item);
      } else {
        travelMenus(item.children);
      }
    });
  }

  function findMatchedMenu(matched) {
    for (const item of matched) {
      if (menuMap.has(item.name)) {
        return menuMap.get(item.name);
      }
    }
  }
</script>

<template>
  <div class="mx-[50px]">
    <div
      class="h-[50px] leading-[50px] bg-[#fff] pl-[15px] text-[#909090] font-[14px] rounded-[3px]"
    >
      <a>
        <icon-left />
        <span>返回个人主页</span>
      </a>
    </div>
    <a-row class="mt-[15px]" :gutter="30">
      <a-col :span="5">
        <div>
          <a-menu mode="pop" showCollapseButton class="h-[650px] rounded-[3px]">
            <a-menu-item v-for="item in menus" :key="item.key" class="mt-[2px]">
              <template #icon v-if="item.icon">
                <component :is="item.icon" />
              </template>
              <span class="text-[14px]">{{ item.title }}</span>
            </a-menu-item>
          </a-menu>
        </div>
      </a-col>
      <a-col :span="19">
        <div>
          <RouterView />
        </div>
      </a-col>
    </a-row>
  </div>
</template>
